<template>
  <PageMain>
    <template #header></template>
    <template #body>
      <div class="MainBox">
        <div class="w-[360px] h-full px-6">
          <a-tabs default-active-key="1">
            <a-tab-pane key="1" title="数据资产">
              <div class="w-full h-full bg-white">
                <div class="mb-3">
                  <SeachInput
                    width="100%"
                    placeholder="搜索"
                    @search="handelSearch"
                    allow-clear
                    @clear="clearData"
                  />
                </div>
                <div class="flex items-center h-[32px] px-3 mb-2" v-if="selectNumber">
                  <span>已选择{{ selectNumber }}项</span>
                  <span class="ml-2 text-[#1459FA] cursor-pointer" @click="selectAll">取消</span>
                </div>
                <div class="w-full bg-white max-h-[600px]">
                  <div>
                    <a-table
                      bordered
                      :show-header="true"
                      :row-selection="TableRowSelectionData"
                      :columns="leftColumns"
                      :data="dataAssert"
                      @select="handleTableData"
                      @select-all="handleTableAll"
                      @page-change="pageChange"
                      row-key="id"
                    >
                      <template #version="{ record }">
                        <span>V{{ record.version }}.0</span>
                      </template>
                    </a-table>
                  </div>
                </div>
              </div>
            </a-tab-pane>
            <a-tab-pane key="2" title="数据资源">
              <div class="w-full h-full bg-white">
                <div class="mb-3">
                  <SeachInput
                    placeholder="搜索"
                    @search="handelResourcesSearch"
                    allow-clear
                    width="100%"
                    @clear="clearResource"
                  />
                </div>
                <div
                  class="flex items-center h-[32px] px-3 mb-2"
                  v-if="selectNumberNaturalResources"
                >
                  <span>已选择{{ selectNumberNaturalResources }}项</span>
                  <span
                    class="ml-2 text-[#1459FA] cursor-pointer"
                    @click="selectAllNaturalResources"
                    >取消</span
                  >
                </div>
                <div class="w-full bg-white max-h-[600px]">
                  <div>
                    <a-table
                      bordered
                      :show-header="true"
                      :row-selection="TableRowSelectionNaturalResourcesData"
                      :columns="middleColumns"
                      :data="dataSource"
                      @select="handleResourcesTableData"
                      @select-all="handleTableAllResources"
                      @page-change="pageResourcesChange"
                      row-key="id"
                    >
                      <template #version="{ record }">
                        <span>V{{ record.version }}.0</span>
                      </template>
                    </a-table>
                  </div>
                </div>
              </div>
            </a-tab-pane>
          </a-tabs>
        </div>

        <div class="w-full">
          <div
            class="w-full h-[56px] p-[16px_0] overflow-hidden box-border flex justify-start items-start"
            style="font-size: 16px; font-weight: bold; color: #394d73"
          >
            选中标的
          </div>
          <div class="w-full bg-white max-h-[660px] overflow-auto">
            <CommonTable
              :columnsData="rightColumns"
              :pageTotal="checkData.length"
              :tableData="checkData"
            >
              <template #version="{ record }">
                <span>V{{ record.version }}.0</span>
              </template>
              <template #optional="{ record }">
                <a-link type="primary" @click="deleteResource(record)">删除</a-link>
              </template>
            </CommonTable>
          </div>
        </div>
      </div>
      <div class="footer flex items-center justify-between">
        <div class="mr-10">
          <a-space>
            <a-button @click="callBack">取消</a-button>
            <a-button type="primary" @click="onCompleteClick">完成</a-button>
          </a-space>
        </div>
      </div>
    </template>
  </PageMain>
</template>

<script lang="ts" setup>
import { computed, onMounted, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
const route = useRoute();
const router = useRouter();
import type { TableRowSelection } from '@arco-design/web-vue';
import { leftColumns, middleColumns, rightColumns } from './use_hooks/useSeletdata';
import {
  getRelatedObjects,
  createRelatedObjects,
  getAssert,
  getSource
} from '@/api/assetManagement/resource_project/index';

const dataAssert = ref([]);
const dataSource = ref([]);
const pageAsswert = ref(1); // 跳转页码
const page_sizeAsswert = ref(10); // 每页显示多少条数据

const pageSource = ref(1); // 跳转页码
const page_sizeSource = ref(10); // 每页显示多少条数据

/**
 * @method 表格配置
 */

const TableRowSelectionData = ref<TableRowSelection>({
  type: 'checkbox', //行选择器的类型
  selectedRowKeys: [], //已选择的行（受控模式）
  defaultSelectedRowKeys: [], //默认已选择的行（非受控模式）
  showCheckedAll: true, //是否显示全选选择器
  title: '', //列标题
  width: undefined, //列宽度
  fixed: false, //是否固定
  checkStrictly: true, //是否开启严格选择模式
  onlyCurrent: false //是否仅展示当前页的 keys（切换分页时清空 keys）
});

const TableRowSelectionNaturalResourcesData = ref<TableRowSelection>({
  type: 'checkbox', //行选择器的类型
  selectedRowKeys: [], //已选择的行（受控模式）
  defaultSelectedRowKeys: [], //默认已选择的行（非受控模式）
  showCheckedAll: true, //是否显示全选选择器
  title: '', //列标题
  width: undefined, //列宽度
  fixed: false, //是否固定
  checkStrictly: true, //是否开启严格选择模式
  onlyCurrent: false //是否仅展示当前页的 keys（切换分页时清空 keys）
});

/*数据资产的分页*/
const pageChange = (val: any) => {
  page.value.page = val;
  getProjectList();
};

/*数据资源的分页*/
const pageResourcesChange = (val: any) => {
  resourcesPage.value.page = val;
  getProjectResourcesList();
};

/**
 * @method 表格复选框逻辑 数据资产
 */
const handleTableData = (rowKeys: string[], rowKey: string, record: any) => {
  if (checkData.value.length === 0) {
    TableRowSelectionData.value.selectedRowKeys = rowKeys;
    checkData.value.push(record);
    return;
  }
  let found = false;
  checkData.value.forEach((item: any, index: number) => {
    if (item.id === rowKey && item.tag === '数据资产') {
      // 找到相同的 key，删除该条数据
      checkData.value.splice(index, 1);
      let idx = TableRowSelectionData.value?.selectedRowKeys?.indexOf(rowKey);
      TableRowSelectionData.value?.selectedRowKeys?.splice(idx as any, 1);
      found = true; // 标记为找到匹配的 key
    }
  });
  // 如果没有找到相同的 key，则向数组中推入新记录
  if (!found) {
    TableRowSelectionData.value.selectedRowKeys = rowKeys;
    checkData.value.push(record);
  }
};

/**
 * @method handleResourcesTableData 表格复选框逻辑 数据资源
 */
const handleResourcesTableData = (rowKeys: string[], rowKey: string, record: any) => {
  if (checkData.value.length === 0) {
    TableRowSelectionNaturalResourcesData.value.selectedRowKeys = rowKeys;
    checkData.value.push(record);
    return;
  }
  let found = false;
  checkData.value.forEach((item: any, index: number) => {
    if (item.id === rowKey && item.tag === '数据资源') {
      // 找到相同的 key，删除该条数据
      checkData.value.splice(index, 1);
      let idx = TableRowSelectionNaturalResourcesData.value?.selectedRowKeys?.indexOf(rowKey);
      TableRowSelectionNaturalResourcesData.value?.selectedRowKeys?.splice(idx as any, 1);
      found = true; // 标记为找到匹配的 key
    }
  });
  // 如果没有找到相同的 key，则向数组中推入新记录
  if (!found) {
    TableRowSelectionNaturalResourcesData.value.selectedRowKeys = rowKeys;
    checkData.value.push(record);
  }
};

/**
 * @method handleTableAll 表格全选
 */
const handleTableAll = (value: boolean) => {
  if (value == true) {
    let ids = dataAssert.value?.map((key: any) => key.id);
    TableRowSelectionData.value.selectedRowKeys = ids;
    dataAssert.value?.forEach((item) => checkData.value.push(item));
  } else {
    TableRowSelectionData.value.selectedRowKeys = [];
    checkData.value = checkData.value.filter((item) => {
      return item?.tag !== '数据资产';
    });
  }
};

/**
 * @method handleTableAllResources 表格全选 数据资源
 */
const handleTableAllResources = (value: boolean) => {
  if (value == true) {
    let ids = dataSource.value?.map((key: any) => key.id);
    TableRowSelectionNaturalResourcesData.value.selectedRowKeys = ids;
    dataSource.value?.forEach((item) => checkData.value.push(item));
  } else {
    TableRowSelectionNaturalResourcesData.value.selectedRowKeys = [];
    checkData.value = checkData.value.filter((item) => {
      return item?.tag !== '数据资源';
    });
  }
};

/**
 * @method  deleteResource 删除数据
 */
const deleteResource = (record: any) => {
  if (record.tag == '数据资产') {
    const ids = TableRowSelectionData.value.selectedRowKeys;
    const index = checkData.value.findIndex(
      (item) => item.id === record.id && item.tag === '数据资产'
    );
    if (index !== -1) {
      checkData.value.splice(index, 1);
    }
    TableRowSelectionData.value.selectedRowKeys = ids?.filter((item) => {
      return item !== record.id;
    });
  } else {
    const ids = TableRowSelectionNaturalResourcesData.value.selectedRowKeys;
    const index = checkData.value.findIndex(
      (item) => item.id === record.id && item.tag === '数据资源'
    );
    if (index !== -1) {
      checkData.value.splice(index, 1);
    }
    TableRowSelectionNaturalResourcesData.value.selectedRowKeys = ids?.filter((item) => {
      return item !== record.id;
    });
  }
};

//数据资产
const selectNumber = computed(() => TableRowSelectionData.value.selectedRowKeys?.length);

//数据资源
const selectNumberNaturalResources = computed(
  () => TableRowSelectionNaturalResourcesData.value.selectedRowKeys?.length
);
const checkData = ref<Resource[]>([]);

/**
 * @method selectAll  取消全选 数据资产
 */
const selectAll = () => {
  if (checkData.value.length === 0) {
    return;
  }
  checkData.value = checkData.value.filter((item: any) => {
    return item.tag !== '数据资产';
  });
  TableRowSelectionData.value.selectedRowKeys = [];
};

/**
 * @method selectAllNaturalResources 取消全选 数据资源
 */
const selectAllNaturalResources = () => {
  // const ids = TableRowSelectionNaturalResourcesData.value.selectedRowKeys;
  if (checkData.value.length === 0) {
    return;
  }
  checkData.value = checkData.value.filter((item: any) => {
    return item.tag === '数据资产';
  });
  TableRowSelectionNaturalResourcesData.value.selectedRowKeys = [];
};

/**
 * @method callBack 取消
 */
const callBack = () => {
  router.push({ name: 'projectIndex' });
};
/**
 * @method  onCompleteClick 完成
 */
const onCompleteClick = async () => {
  const params = {
    id: route.query.id as string,
    resources: checkData.value
  };
  const res = await createRelatedObjects(params);
  if (res.code === '00000') {
    return router.push({ name: 'projectIndex' });
  }
};
interface Resource {
  code: string;
  id: string;
  name: string;
  version: string;
  tag: string;
}
//数据资产
const page = ref({
  page: 1,
  page_size: 30,
  name: ''
});

//数据资源
const resourcesPage = ref({
  page: 1,
  page_size: 30,
  name: ''
});

/**
 * @method getListInfo 获取资产项目中已关联的数据
 */
const getListInfo = async () => {
  const { data, code } = await getRelatedObjects(route.query.id as string);
  if (code === '00000') {
    checkData.value =
      data?.map((item: any) => ({
        id: item.id,
        tag: item.tag,
        name: item.name,
        version: item.version
      })) || [];
    TableRowSelectionData.value.selectedRowKeys = checkData.value
      .filter((item: any) => item.tag === '数据资产')
      .map((item: any) => item.id);
    TableRowSelectionNaturalResourcesData.value.selectedRowKeys = checkData.value
      .filter((item: any) => item.tag === '数据资源')
      .map((item: any) => item.id);
  }
};

/**
 * @method getProjectList 获取数据资产列表
 */
const getProjectList = async () => {
  const { data, code } = await getAssert({
    page: pageAsswert.value,
    page_size: page_sizeAsswert.value,
    key: page.value.name,
    all_version: 2
  });
  if (code === '00000') {
    dataAssert.value = data.map((item: any) => ({
      id: item.id,
      tag: '数据资产',
      name: item.name,
      version: item.version
    }));
  }
};

/**
 * @method getProjectResourcesList 获取数据资源列表
 */
const getProjectResourcesList = async () => {
  const { data, code } = await getSource({
    page: pageSource.value,
    page_size: page_sizeSource.value,
    name: resourcesPage.value.name,
    all_version: 2
  });
  if (code === '00000') {
    dataSource.value = data.map((item: any) => ({
      id: item.id,
      tag: '数据资源',
      name: item.name,
      version: item.version
    }));
  }
};

/**
 * @method handelSearch 数组资产搜索
 */
const handelSearch = (value: any) => {
  page.value.name = value;
  getProjectList();
};
/**
 * @method handelResourcesSearch 数组资源搜索
 */
const handelResourcesSearch = (value: any) => {
  resourcesPage.value.name = value;
  getProjectResourcesList();
};

/**
 * @method clearResource 数组资源清空
 */
const clearResource = () => {
  resourcesPage.value.name = '';
  getProjectList();
};

/**
 * @method clearData 数组资产清空
 */
const clearData = () => {
  page.value.name = '';
  getProjectList();
};

onMounted(() => {
  getListInfo();
  getProjectList();
  getProjectResourcesList();
});
</script>

<style lang="less" scoped>
.MainBox {
  width: 100%;
  height: 100%;
  display: flex;
}
.title {
  font-size: 20px;
  font-weight: bold;
  line-height: 32px;
  letter-spacing: 0;
  color: #394d73;
}
:deep(.arco-table-tr) {
  height: 30px;
}
:deep(.arco-tabs-nav-type-line .arco-tabs-tab-title) {
  font-size: 16px;
  font-weight: bold;
}

.footer {
  height: 64px;
  position: fixed;
  left: 220px;
  bottom: 0;
  width: calc(100vw - 220px);
  color: white;
  text-align: center;
  padding: 10px;
  box-shadow: 0 0 6px 0 rgba(57, 77, 115, 0.1);
  display: flex;
  justify-content: flex-end;
}
:deep(.arco-table-element) {
  thead {
    .arco-table-tr {
      .arco-table-th {
        background: #f7f9fc !important;
        color: #394d73 !important;
        font-size: 14px !important;
        font-weight: 400;
      }
    }
  }
  tbody {
    .arco-table-tr {
      .arco-table-td {
        //background: #EBF0FA !important;
        font-size: 14px !important;
        font-weight: 400;
        color: #465a80 !important;
      }
    }
  }
}
</style>
